package middlewares

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

// 跨域请求处理 (cross origin resource share)
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin")

		if origin != "" {
			// 设置允许跨域的域名，* 代表允许任意域名跨域
			c.Header("Access-Control-Allow-Origin", "*") // 可将 * 替换为指定的域名
			// 跨域允许的请求方式
			c.Header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS,UPDATE")
			// 允许的 header 类型
			c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
			c.Header("Access-Control-Allow-Credentials", "true")
			c.Set("content-type", "application/json") // 返回格式
		}

		if method == "OPTIONS" {
			// c.JSON(http.StatusOK, "Options Request!")
			c.AbortWithStatus(http.StatusNoContent)
		}

		// 继续处理下面的请求逻辑
		c.Next()
	}
}
